#!/usr/bin/python
# yongming.li

import os
import string
from   Myconfig import *
from CPUChart import *

#MemTotal:         477804 kB
#MemFree:           12472 kB
#Buffers:            2532 kB
#Cached:           176128 kB


class MemMonitor:
	def __init__(self):
                self.name = 'mem'
		self.MemTotal = ''
		self.MemFree = ''
		self.Buffers = ''
		self.Cached = ''
                self.filename =  './out/mem.txt'   
                self.memcontainer=[]
                self.cpuchart = CPUChart();


        def dump(self):
            print 'MemTotal %-10s'%(self.MemTotal)+'MemFree %-10s'%(self.MemFree) \
                  +'Buffers %-10s'%(self.Buffers)  +'Cached %-10s'%(self.Cached) 

        def  parse (self,s): 
           s=s.strip()
           memitem=string.split(s)
           #print  'memory'
           if 'MemTotal'  in s:
               self.MemTotal=memitem[1]

               os.system('echo %s > '%(s)+ self.filename)
               return -1 
           if 'MemFree'  in s:
               self.MemFree=memitem[1]
               os.system('echo %s >> '%(s)+ self.filename)
               return -1 
           if 'Buffers'  in s:
               self.Buffers=memitem[1]
               os.system('echo %s >> '%(s)+ self.filename)
               return -1 
           if 'Cached'  in s:
              os.system('echo %s >> '%(s)+ self.filename)
              self.Cached=memitem[1]
              free =  float(self.MemFree)+float(self.Buffers)+float(self.Cached)
              used =  float(self.MemTotal)-free
              memrate = ((used)/float(self.MemTotal))*100
              #print  memrate
              self.cpuchart.showroundmeter('mem',memrate);
              if len(self.memcontainer) > Myconfig.samplecount:
                  del self.memcontainer[0]    
              self.memcontainer.append(memrate);
              self.cpuchart.showsimplearea('mem',self.memcontainer);
           return 0 

        def  start(self):
                 lines = os.popen("adb shell cat /proc/meminfo").readlines()
                 for  line  in lines: 
                     if self.parse(line) ==0:
                         break
                     


